<template>
  <el-dialog v-model="uploadDialogVisible" title="上传图片" width="50%">
    <el-upload
      class="image-uploader"
      :action="apiUrl"
      :file-list="fileList"
      :on-remove="handleRemove"
      :limit="1"
      list-type="picture-card"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :on-error="handleError"
      :headers="UploadHeaders"
      :before-upload="beforeUpload"
      drag
    >
      <template #default>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
      </template>
    </el-upload>
    <template #footer>
      <el-button @click="closeUploadDialog">取消</el-button>
      <el-button type="primary" @click="confirmUpload">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue"
import { ElMessage } from "element-plus"
import { getToken } from "@/utils/cache/cookies"
import { UploadFilled } from "@element-plus/icons-vue"

const apiUrl = import.meta.env.VITE_BASE_API + "/Common/uploadImage"
const UploadHeaders = {
  "X-Token": getToken()
}

// Emits 定义返回事件
const emit = defineEmits(["upload-complete", "upload-cancel"])

// 控制上传弹框
const uploadDialogVisible = ref(false)

// 当前调用方的标识符
const currentContextKey = ref<string>("")

// 上传文件列表
const fileList = ref<any[]>([])
const fileLists = ref<any[]>([])

// 当前预览图片的 URL
const previewUrl = ref("")

// 打开上传弹框，并传入调用方标识符
const openUploadDialog = (contextKey: string) => {
  currentContextKey.value = contextKey // 设置当前调用方标识符
  uploadDialogVisible.value = true
}
defineExpose({ openUploadDialog })
// 关闭上传弹框
const closeUploadDialog = () => {
  uploadDialogVisible.value = false
  resetUploadDialog() // 重置弹框数据
  // 触发取消事件，传递当前 contextKey
  emit("upload-cancel", currentContextKey.value)
}
// 重置上传弹框的状态
const resetUploadDialog = () => {
  fileList.value = [] // 清空文件列表
  currentContextKey.value = "" // 清空调用方标识符
  previewUrl.value = "" // 清空预览 URL
}

// 确认上传操作
const confirmUpload = () => {
  // 将上传完成结果通过 emit 传递
  emit("upload-complete", {
    contextKey: currentContextKey.value,
    fileList: fileLists.value
  })
  resetUploadDialog() // 重置弹框数据
  uploadDialogVisible.value = false
}

// 删除图片
const handleRemove = (file: any, fileList: any[]) => {
  ElMessage.success("图片已删除")
  console.log(fileList)
  console.log(file)
}

// 上传成功
const handleSuccess = (response: any, file: any, fileList: any[]) => {
  ElMessage.success("图片上传成功")
  // 更新 fileList
  fileLists.value = response.data
  console.log(file)
  console.log(fileList)
}

// 上传失败
const handleError = (error: any, file: any, fileList: any[]) => {
  ElMessage.error("图片上传失败")
  // 从 fileList 中移除失败的文件
  const index = fileList.findIndex((item) => item.uid === file.uid)
  if (index !== -1) {
    fileList.splice(index, 1)
  }
}

// 上传前校验图片
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/")
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error("上传文件必须是图片格式!")
    return false
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!")
    return false
  }
  return true
}

// 超出限制处理
const handleExceed = () => {
  ElMessage.warning("最多只能上传 1 张图片")
}
</script>

<style scoped lang="scss">
.image-uploader {
  text-align: center;
  width: 100%;
}

.el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.el-icon--upload {
  font-size: 22px;
  color: #8c939d;
  margin-bottom: 8px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload-list--picture-card) {
  display: flex;
}
</style>
